<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 消息提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 进度条区域 -->
      <el-steps :space="200" :active="activeIndex - 0 " finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 验证表单的区域 -->
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="ruleFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- tab栏区域 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addRuleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addRuleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addRuleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- props是级联选择的配置项，设置数据该怎么显示 options 绑定的是数据源 v-model是双向数据绑定的用户点中的id值，数组-->
              <el-cascader
                v-model="addRuleForm.goods_cat"
                :options="cateList"
                expand-trigger="hover"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1,index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- on-success监听图片上传成功的事件 -->
            <el-upload
              :action="actionURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本框编辑组件 -->
            <quill-editor v-model="addRuleForm.goods_introduce"></quill-editor>
            <!-- <div style="clear : both"></div> -->
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addGoods" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片的对话框 -->
    <el-dialog title="图片预览" :visible.sync="prviewDialogVisible" width="50%">
      <img :src="urlPath" style="width : 100%" />
    </el-dialog>
  </div>
</template>

<script>
// 导入克隆模块
import _ from 'lodash'
import { async } from 'q';

export default {
  data() {
    return {
      activeIndex: '0',
      // 表单数据对象
      addRuleForm: {
        goods_name: '',
        goods_price: '0',
        goods_weight: '0',
        goods_number: '0',
        // 商品分类id的数组
        goods_cat: [],
        // 图片上传的临时路径，数组里面是对象，文档要求的格式
        pics: [],
        goods_introduce: '',
        // 商品的参数数组，包括动态和静态，文档要求上传的格式
        attrs : []
      },
      // 动态参数列表
      manyData: [],
      // 静态属性列表
      onlyData: [],
      // 储存分类数据
      cateList: [],
      // 图片上传的路径
      actionURL: 'http://www.klxin.cn:8888/api/private/v1/upload',
      // 设置请求头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的绝对路径
      urlPath: '',
      // 图片预览框默认关闭
      prviewDialogVisible: false,
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 表单验证规则
      addRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获得分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res.data)
      this.cateList = res.data
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据列表失败')
      }
    },
    // 当选中框发生改变时
    handleChange() {
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = []
      }
    },
    // 当tab栏发生切换时触发事件
    beforeLeave(activeName, oldActiveName) {
      // 当选中项为基本信息，且没有选中第三级选项时,不允许切换
      if (oldActiveName == 0 && this.addRuleForm.goods_cat.length !== 3) {
        this.$message.info('请选择商品分类')
        return false
      }
    },
    // 当其中的一个tab栏被点击时，触发事件
    async tabClick() {
      // 当点击的是参数列表时，向服务器发送请求
      if (this.activeIndex === '1') {
        console.log(this.cateIdThree)

        const { data: res } = await this.$http.get(
          `categories/${this.cateIdThree}/attributes`,
          { params: { sel: 'many' } }
        )
        console.log(res, 1111)
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')
        }
        // 将attr_vals字符串变成数组，用户页面遍历渲染
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
})
        // 将服务器返回的参数列表保存在data中，用于渲染页面
        this.manyData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateIdThree}/attributes`,
          {
            params: { sel: 'only' }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败！')
        }

        console.log(res.data)
        this.onlyData = res.data
      }
    },
    // 点击图片的时候实现预览功能
    handlePreview(file) {
      // 将服务器返回的绝对路径存储在data中
      this.urlPath = file.response.data.url
      // 打开对话框
      this.prviewDialogVisible = true
    },
    // 实现图片的移除功能
    handleRemove(res) {
      console.log(res)
      // 获取要删除的图片的临时路径
      const removePath = res.response.data.tmp_path
      // 获取临时路径在数组中的索引值
      const i = this.addRuleForm.pics.findIndex(item => item.pic === removePath)
      // 从数组中将这个索引对应的临时路径删除
      this.addRuleForm.pics.splice(i, 1)
      console.log(this.addRuleForm)
    },
    // 图片上传成功时
    uploadSuccess(res) {
      console.log(res)
      // 构建一个图片路径对象，上传参数要求是对象格式
      const picPath = {
        pic: res.data.tmp_path
      }
      this.addRuleForm.pics.push(picPath)
      console.log(this.addRuleForm)
    },
    // 添加商品按钮
    addGoods() {
      // 进行表单验证
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必填项')
        // 验证成功时
        // 将goods_cat数组变成以","分割成的列表,需要克隆 addRuleForm对象
        const form = _.cloneDeep(this.addRuleForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form);
        // 循环遍历动态参数，得到"attr_id，attr_value的对象
        this.manyData.forEach(item => {
          const newInfo = {
            attr_id : item.attr_id,
            attr_value : item.attr_vals.join(' ')
          }
          this.addRuleForm.attrs.push(newInfo)
        })
         // 循环遍历静态属性，得到"attr_id，attr_value的对象
        this.onlyData.forEach(item => {
          const newInfo = {
            attr_id : item.attr_id,
            attr_value : item.attr_vals
          }
          this.addRuleForm.attrs.push(newInfo) 
        })
        form.attrs = this.addRuleForm.attrs
        // console.log(this.addRuleForm.attrs);
        // console.log(form);
        // 发送请求，提交商品
        const {data : res} = await this.$http.post('goods',form)
        console.log(form);
        
        console.log(res);
        
        if(res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 得到第三级id
    cateIdThree() {
      if (this.addRuleForm.goods_cat.length === 3) {
        return this.addRuleForm.goods_cat[2]
      }
    }
  }
}
</script>
  
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
// .quill-editor {
//   height: 200px;
// }
.addGoods {
  margin-top: 15px !important;
}
.ql-editor {
  min-height: 150px;
}
</style>